//
//  VC5AudioPlayer.swift
//  ChapterAll
//
//  Created by Kevin on 2020/4/24.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit
import AVFoundation
import MediaPlayer

class VC5AudioPlayer: UIViewController {
    
    var timmer:Timer?
    var mPlayer:AVAudioPlayer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = URL(fileURLWithPath: Bundle.main.path(forResource: "qiansixi", ofType: "mp3")!)
        mPlayer = try? AVAudioPlayer(contentsOf: url)
        mPlayer?.prepareToPlay()
//        mPlayer?.play()
        
        timmer = Timer.scheduledTimer(timeInterval: 1/60.0, target: self, selector: #selector(updateProcess), userInfo: nil, repeats: true)
        timmer?.fire()
        
        
        var dict = Dictionary<String,Any>()
        dict[MPMediaItemPropertyTitle] = "牛仔很忙"
        dict[MPMediaItemPropertyArtist] = "周杰伦"
        dict[MPMediaItemPropertyAlbumTitle] = "专辑名称"
        dict[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: CGSize(width: 100, height: 100), requestHandler: { (size) -> UIImage in
            return UIImage(named: "ic_action_home")!
        })
        dict[MPMediaItemPropertyPlaybackDuration] = NSNumber(value: 300)
        dict[MPMediaItemPropertyBookmarkTime] = NSNumber(value: 150)
        MPNowPlayingInfoCenter.default().nowPlayingInfo = dict
    }
    
    // 歌曲时间
    @IBOutlet weak var songTime: UILabel!
    
    // 停止播放
    @IBAction func clickStop(_ sender: UIButton) {
        if mPlayer!.isPlaying {
            mPlayer?.stop()
        }
    }
    
    // 播放音乐
    @IBAction func clickPlay(_ sender: UIButton) {
        if mPlayer!.isPlaying {
            return
        }
        mPlayer?.play()
    }
    
    // 暂停播放
    @IBAction func clickPause(_ sender: UIButton) {
        if mPlayer!.isPlaying {
            mPlayer?.pause()
        }
    }
    
    // 速度
    @IBAction func clickRate(_ sender: UISlider) {
        mPlayer?.rate = sender.value + 50
    }
    
    // 声道
    @IBAction func clickSound(_ sender: UISlider) {
        mPlayer?.pan = (sender.value - 0.5) * 2
    }
    
    // 音量
    @IBAction func clickVolume(_ sender: UISlider) {
        mPlayer?.volume = sender.value
    }
    
    
    @objc func updateProcess() -> Void {
        let duration = mPlayer?.duration
        let current = mPlayer?.currentTime
        
        let m1 = Int(current!) / 60
        let s1 = Int(current!) % 60
        
        let m2 = Int(duration!) / 60
        let s2 = Int(duration!) % 60
        
        songTime.text = String(format: "%02d:%02d/%02d:%02d", m1,s1,m2,s2)
    }
}
